﻿'use strict';

app.factory('listStorage', function ($q, $http, $resource) {

    //If we store Items in here and return this, as this is a singleton the State is here,
    //o if we wanted to pass the same data between controllers it could access it here
    var _items = [];

    return {
        items: _items,
        getItems: function ($scope) {
            //Im post processign here so need to create a promise rather than get http to return one.
            //Besides this is normal the amount of post processing I've seen in Controller examples
            //manipulating returned data is scary its not supposed to be like that.
            var deferred = $q.defer();
            var url = $scope.appWebUrl + "/_api/web/lists/getByTitle('Tasks')/items?$select=ID,Title,Body";
            _items = [];

            $http({
                method: 'GET',
                url: url,
                headers: { "Accept": "application/json; odata=verbose" }
            })
            .success(function (data, status, headers, config) {

                angular.forEach(data.d.results, function (taskItem) {
                    _items.push({
                        ID: taskItem.ID,
                        Title: taskItem.Title,
                        Description: taskItem.Body
                    });
                })

                deferred.resolve(_items);
            })
            .error(function (data, status, headers, config) {
                console.log("Error " + status);
                deferred.reject(status);
            });

            return deferred.promise;
        },
        getItemsSPServices: function ($scope) {

            var listContents;
            //return an angular promise, because Im post processing, but also SPServices uses jQuery
            //promises, not sure if you can mix the two.
            var deferred = $q.defer();
            _items = [];

            $().SPServices({
                operation: "GetListItems",
                webURL: "..",   //When accessing a list in the App Space you have to set this URL
                async: true,
                listName: "Tasks",
                CAMLViewFields: "<ViewFields xmlns='' > \
	    						    <FieldRef Name='ID' /> \
	    						    <FieldRef Name='Title' /> \
	    						    <FieldRef Name='Body' /> \
	    					    </ViewFields> ",
                CAMLRowLimit: 0
            })
            .then(
                 function (data, status) {
                     if (status == "success") {
                         _items = $(data).SPFilterNode("z:row").map(function () {
                             return {
                                 ID: $(this).attr('ows_ID'),
                                 Title: $(this).attr('ows_Title'),
                                 Description: $(this).attr('ows_Body'),
                                 Created: $(this).attr('ows_Created')
                             };
                         });

                         $scope.$apply(deferred.resolve(_items));
                     } else {
                         $scope.$apply(deferred.reject(status));
                     }
                 }
              )
            .fail(function (error) {
                $scope.$apply(deferred.reject(error.status + " " + error.statusText));
            })

            return deferred.promise;
        }

    };
});

